//
//  QRCodeViewController.swift
//  WEIBO_SWIFT
//
//  Created by 岳挺 on 15/6/30.
//  Copyright © 2015年 yueting. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController, UITabBarDelegate {
    //背景图片高
    @IBOutlet weak var bgImageHeight: NSLayoutConstraint!
    
    @IBOutlet weak var tabBarView: UITabBar!
    //扫描图片bottom约束
    @IBOutlet weak var scanImageBottom: NSLayoutConstraint!

    //脉冲图片view
    @IBOutlet weak var scanImageView: UIImageView!
    
    //扫描框图片
    @IBOutlet weak var bgImageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置默认选中为第一个
        tabBarView.selectedItem = tabBarView.items![0]
    }
    
    @IBAction func closeQRCode(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @IBAction func presentMyQRcode(sender: UIButton) {
//        presentViewController(QRCodeMyViewController(), animated: true, completion: nil)
        navigationController?.pushViewController(QRCodeMyViewController(), animated: true)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        startAnimaiton()
        startScanQRCode()
    }
    
    func startAnimaiton (){
        scanImageBottom.constant = -bgImageHeight.constant
        self.view.layoutIfNeeded()
        UIView.animateWithDuration(2.0) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanImageBottom.constant = self.bgImageHeight.constant

            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - tabBar代理方法
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        bgImageHeight.constant = scanImageView.bounds.size.width * CGFloat(item.tag) * 0.5
        scanImageBottom.constant = -bgImageHeight.constant
        view.layoutIfNeeded()
        startAnimaiton()
    }
    
    // MARK: - 二维码扫描
    func startScanQRCode (){
        //判断能否添加输入设备
        if !session.canAddInput(inputDevice){
            print("无法添加设备")
        }
        
        //判断能否添加输出设备
        if !session.canAddOutput(outputData){
            print("无法添加输出数据")
        }
        
        //添加输入设备输出设备
//        session.addInput(inputDevice)
//        session.addOutput(outputData)
//        print(outputData.availableMetadataObjectTypes)
//        
    }
    
    // MARK: - 懒加载
    //桥梁session
    lazy var session = AVCaptureSession()
    
    //输入设备
    lazy var inputDevice : AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do{
            return try AVCaptureDeviceInput(device: device)
        } catch {
            print(error)
        }
        return nil
    }()
    
    //输出数据
    lazy var outputData: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
}
